package blue.http.internal.core.message;

import blue.base.core.util.NumberUtil;
import blue.http.core.message.UploadFile;
import io.netty.handler.codec.http.multipart.FileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * 上传文件对象的默认实现
 *
 * @author zhengj
 * @since 1.0 2017年3月27日
 */
public class DefaultUploadFile implements UploadFile {
	private static Logger logger = LoggerFactory.getLogger(DefaultUploadFile.class);

	private int size;
	private Path path;
	private String contentType;
	private String originalName;

	public DefaultUploadFile(FileUpload fileUpload) throws IOException {
		contentType = fileUpload.getContentType();
		originalName = fileUpload.getFilename();
		if (!fileUpload.isInMemory()) {
			File file = fileUpload.getFile();
			if (file != null) {
				size = (int) file.length();
				this.path = file.toPath();
			}
			return;
		}
		size = fileUpload.get().length;
		path = Files.createTempFile(null, null);
		Files.write(path, fileUpload.get());
		logger.info("Write file：{} - {} bytes", path, size);
	}

	@Override
	public int getSize() {
		return size;
	}

	@Override
	public String getContentType() {
		return contentType;
	}

	@Override
	public String getOriginalName() {
		return originalName;
	}

	@Override
	public Path getPath() {
		return path;
	}

	@Override
	public InputStream getInputStream() throws IOException {
		return Files.newInputStream(path);
	}

	@Override
	public void delete() {
		if (path == null)
			return;

		try {
			Files.deleteIfExists(path);
		} catch (IOException e) {
			logger.warn("Delete file error, ", e);
		}
	}

	@Override
	public String toString() {
		return String.format("%s [%s] - %s [%d bytes(%s)]", originalName, contentType, path, size, NumberUtil.byteFormat(size));
	}


}
